package com.mallbook.controller.servlet.admin;

import com.mallbook.model.exception.ServiceException;
import com.mallbook.model.pojo.Category;
import com.mallbook.model.pojo.Goods;
import com.mallbook.model.pojo.PageBean;
import com.mallbook.model.service.CategoryService;
import com.mallbook.model.service.GoodsService;
import com.mallbook.model.utils.MallDefaultConfig;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-07-01
 */
@WebServlet("/admin/goods")
@MultipartConfig
public class GoodsServlet extends HttpServlet {
    private GoodsService goodsService = new GoodsService();
    private CategoryService categoryService = new CategoryService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String opr = req.getParameter("opr");
        if (opr == null) {
            req.getRequestDispatcher("/WEB-INF/admin/goods_add.jsp").forward(req, resp);
            return;
        }
        switch (Objects.requireNonNull(opr)) {
            case "initAdd":
                doInitAdd(req, resp);
                break;
            case "add":
                doAdd(req, resp);
                break;
            case "del":
                doDel(req, resp);
                break;
            case "select":
                doSelect(req, resp);
                break;
            case "updateSelect":
                doUpdateSelect(req, resp);
                break;
            case "update":
                doUpdate(req, resp);
                break;
        }
    }

    private void doDel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("gid"); // id
        Integer gid = Integer.parseInt(id);
        try {
            goodsService.delGoods(gid);
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }
        resp.sendRedirect("/admin/goods?opr=select");
    }

    private void doUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("gid"); // id
        Integer gid = null;
        if (id != null) {
            gid = Integer.parseInt(id);

        }
        String author = req.getParameter("author"); // 作者
        String gAuthor = null;
        if (author != null) {
            gAuthor = new String(author.getBytes("iso8859-1"), StandardCharsets.UTF_8);

        }
        String publisher = req.getParameter("publisher");// 出版社
        String gPublisher = null;
        if (publisher != null) {
            gPublisher = new String(publisher.getBytes("iso8859-1"), StandardCharsets.UTF_8);

        }
        String pubTime = req.getParameter("pubTime");// 出版时间
        String gPubTime = null;
        if (pubTime != null) {
            gPubTime = new String(pubTime.getBytes("iso8859-1"), StandardCharsets.UTF_8);

        }
        String categoryId = req.getParameter("categoryId");// 所属分类
        String salesNum = req.getParameter("salesNum");// 销量
        String stock = req.getParameter("stock");// 库存
        Integer gStock = null;
        if (stock != null) {
            gStock = Integer.parseInt(stock);

        }
        String marketPrice = req.getParameter("marketPrice");// 市场价格
        if (marketPrice == null) {
            marketPrice = "0";
        }
        String salesPrice = req.getParameter("salesPrice");// 销售价格
        if (salesPrice == null) {
            salesPrice = "0";
        }
        String description = req.getParameter("description");// 产品描述
        String gDescription = null;
        if (description != null) {
            gDescription = new String(description.getBytes("iso8859-1"), StandardCharsets.UTF_8);

        }
        String newest = req.getParameter("newest");// 是否最新
        String hot = req.getParameter("hot");// 是否热卖
        // 获取提交上来的文件
        Part part = req.getPart("file");
        String DBPath = null;

        // 获取提交的文件名
        String submittedFileName = part.getSubmittedFileName();
        if (!submittedFileName.equals("")) {
            // 产生一个32位的唯一字符串
            String fileName = UUID.randomUUID().toString().replace("-", "");
            // 获取文件后缀名
            String suffix = submittedFileName.substring(submittedFileName.lastIndexOf("."));
            // 获取站点文件存放路径
            String path = getServletContext().getRealPath("/goodsImg");
            // 删除原来的图片文件
            Goods goods = goodsService.getGoodsById(gid);
            String delPath = getServletContext().getRealPath("/") + goods.getImg();
            File delFile = new File(delPath);
            if (!delFile.delete()) {
                resp.getWriter().write("图片更新失败！！！");
                return;
            }
            // 将文件写入磁盘
            part.write(path + "/" + fileName + suffix);
            DBPath = "goodsImg/" + fileName + suffix;
        }

        Integer isNew;
        if ("1".equals(newest)) {
            isNew = 1;
        } else {
            isNew = -1;
        }
        int isHot;
        if ("1".equals(hot)) {
            isHot = 1;
        } else {
            isHot = -1;
        }
        Integer gCategoryId = Integer.parseInt(categoryId);
        Integer gSalesNum = Integer.parseInt(salesNum);
        try {
            goodsService.updateGoods(gAuthor, gPublisher, gPubTime, gStock, marketPrice, salesPrice, gDescription, isNew, isHot, DBPath, gCategoryId, gSalesNum, 1, gid);
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }
        resp.sendRedirect("/admin/goods?opr=select");
    }

    private void doUpdateSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        System.out.println(id);
        try {
            Goods goods = goodsService.getGoodsById(id);
            req.setAttribute("goods", goods);
            List<Category> categoryList = categoryService.getAllCategoryIsNotDel(); // 查询所有商品分类
            req.setAttribute("categories", categoryList);
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }
        req.getRequestDispatcher("/WEB-INF/admin/goods_update.jsp").forward(req, resp);

    }

    private void doSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String p = req.getParameter("p");
        String pSize = req.getParameter("pSize");

        String categoryID = req.getParameter("categoryId");
        String name = req.getParameter("name");
        String minPrice = req.getParameter("minPrice");
        String maxPrice = req.getParameter("maxPrice");
        Goods goods = new Goods();
        Category category = new Category();
        if (categoryID == null || categoryID.equals("0")) {
            category.setId(null);
        } else {
            category.setId(Integer.parseInt(categoryID));
        }
        goods.setCategory(category);
        goods.setBookName(name);
        if (minPrice != null && !minPrice.equals("")) {
            goods.setMinPrice(new BigDecimal(Integer.parseInt(minPrice)));
        }
        if (maxPrice != null && !maxPrice.equals("")) {
            goods.setMaxPrice(new BigDecimal(Integer.parseInt(maxPrice)));
        }
        req.setAttribute("goods", goods);

        Integer page = null;
        if (p == null || p.equals("")) {
            page = 1;
        } else {
            page = Integer.parseInt(p);
        }
        if (pSize != null && !pSize.equals("")) {
            MallDefaultConfig.GOODS_PAGE_SIZE = Integer.parseInt(pSize);
        } else {
            MallDefaultConfig.GOODS_PAGE_SIZE = 5;
        }
        try {
            List<Category> categoryList = categoryService.getAllCategoryIsNotDel(); // 查询所有商品分类
            req.setAttribute("categories", categoryList);
            PageBean<Goods> goodsPageBean = goodsService.getGoodsByCondition(goods, page);
            req.setAttribute("pageBean", goodsPageBean);
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }

        req.getRequestDispatcher("/WEB-INF/admin/goods_list.jsp").forward(req, resp);
    }

    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name"); // 名称
        String gName = new String(name.getBytes("iso8859-1"), StandardCharsets.UTF_8);
        String isbn = req.getParameter("ISBN"); // 商品编号
        String gISBN = new String(isbn.getBytes("iso8859-1"), StandardCharsets.UTF_8);
        String author = req.getParameter("author"); // 作者
        String gAuthor = new String(author.getBytes("iso8859-1"), StandardCharsets.UTF_8);
        String publisher = req.getParameter("publisher");// 出版社
        String gPublisher = new String(publisher.getBytes("iso8859-1"), StandardCharsets.UTF_8);
        String pubTime = req.getParameter("pubTime");// 出版时间
        String gPubTime = new String(pubTime.getBytes("iso8859-1"), StandardCharsets.UTF_8);
        String categoryId = req.getParameter("categoryId");// 所属分类
        String salesNum = req.getParameter("salesNum");// 销量
        String stock = req.getParameter("stock");// 库存
        String marketPrice = req.getParameter("marketPrice");// 市场价格
        String salesPrice = req.getParameter("salesPrice");// 销售价格
        String description = req.getParameter("description");// 产品描述
        String gDescription = new String(description.getBytes("iso8859-1"), StandardCharsets.UTF_8);
        String newest = req.getParameter("newest");// 是否最新
        String hot = req.getParameter("hot");// 是否热卖
        // 获取提交上来的文件
        Part part = req.getPart("file");
        String DBPath = null;
        // 获取提交的文件名
        String submittedFileName = part.getSubmittedFileName();
        if (!submittedFileName.equals("")) {
            // 产生一个32位的唯一字符串
            String fileName = UUID.randomUUID().toString().replace("-", "");
            // 获取文件后缀名
            String suffix = submittedFileName.substring(submittedFileName.lastIndexOf("."));
            // 获取站点文件存放路径
            String path = getServletContext().getRealPath("/goodsImg");
            // 文件不存在时新建文件夹
            File file = new File(path);
            if (!file.isDirectory()) {
                file.mkdirs();
            }
            // 将文件写入磁盘
            part.write(path + "/" + fileName + suffix);
            DBPath = "goodsImg/" + fileName + suffix;
        }
        int isNew;
        if ("1".equals(newest)) {
            isNew = 1;
        } else {
            isNew = -1;
        }
        int isHot;
        if ("1".equals(hot)) {
            isHot = 1;
        } else {
            isHot = -1;
        }
        int gStock=0;
        if (!stock.isEmpty()){
            gStock = Integer.parseInt(stock);
        }
        int gCategoryId=0;
        if (!categoryId.isEmpty()){
            gCategoryId = Integer.parseInt(categoryId);
        }
        int gSalesNum=0;
        if (!salesNum.isEmpty()){
            gSalesNum = Integer.parseInt(salesNum);
        }
        if (marketPrice.isEmpty()){
            marketPrice="0";
        }
        if (salesPrice.isEmpty()){
            salesPrice="0";
        }

//        Integer gStock = Integer.parseInt(stock);
//        Integer gCategoryId = Integer.parseInt(categoryId);
//        Integer gSalesNum = Integer.parseInt(salesNum);
        try {
            goodsService.addGoods(gName, gAuthor, gPublisher, gPubTime, gISBN, gStock, marketPrice, salesPrice, gDescription, isNew, isHot, DBPath, gCategoryId, gSalesNum);
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }
        resp.sendRedirect("/admin/goods?opr=initAdd");
    }

    private void doInitAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Category> categoryList = categoryService.getAllCategoryIsNotDel();
            req.setAttribute("categories", categoryList);
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }
        req.getRequestDispatcher("/WEB-INF/admin/goods_add.jsp").forward(req, resp);
    }
}
